#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
void CreateMatrix(SMatrix *matrix)
{
     FILE *fp = fopen("Matrix", "r");
     if (fp == NULL)
          exit(1);
     fscanf(fp, "%d %d", &matrix->mu, &matrix->nu);
     int value;
     int k = 0;
     for (int i = 0; i < matrix->mu; ++i)
     {
          for (int j = 0; j < matrix->nu; ++j)
          {
               fscanf(fp, "%d", &value);
               if (value)
               {
                    matrix->data[k].e = value;
                    matrix->data[k].i = i;
                    matrix->data[k].j = j;
                    k++;
               }
          }
     }
     matrix->tu = k;
     fclose(fp);
}
void PrintMatrix(SMatrix *matrix)
{
     printf("row = %d,col = %d\n", matrix->mu, matrix->nu);
     for (int i = 0; i < matrix->tu; i++)
     {
          printf("(%d,%d,%d)\n", matrix->data[i].i, matrix->data[i].j, matrix->data[i].e);
     }
}
void CopyMatrix(SMatrix *matrix, SMatrix *m)
{
     m->mu = matrix->mu;
     m->nu = matrix->nu;
     m->tu = matrix->tu;
     for (int i = 0; i < m->tu; i++)
     {
          m->data[i].e = matrix->data[i].e;
          m->data[i].i = matrix->data[i].i;
          m->data[i].j = matrix->data[i].j;
     }
}
void AddMatrix(SMatrix *matrix, SMatrix *N, SMatrix *M)
{
     //数学问题，没有编程障碍
}
void SubMatrix(SMatrix *matrix, SMatrix *N, SMatrix *M)
{
     //数学问题，没有编程障碍
}
void TransposeMatrix(SMatrix *M, SMatrix *N)
{
     N->mu = M->nu;
     N->nu = M->mu;
     N->tu = M->tu;
     int q = 0;
     for (int col = 0; col < M->nu; ++col)
     {
          for (int p = 0; p < M->tu; p++)
               if (M->data[p].j == col)
               {
                    N->data[q].i = M->data[p].j;
                    N->data[q].j = M->data[p].i;
                    N->data[q].e = M->data[p].e;
                    q++;
               }
     }
}
void FastTransposeMatrix(SMatrix *M, SMatrix *N)
{
     N->mu = M->nu;
     N->nu = M->mu;
     N->tu = M->tu;
     int *num = malloc(sizeof(int) * M->tu);
     int *cpot = malloc(sizeof(int) * M->nu);
     if (num == NULL || cpot == NULL)
          return;
     if (N->tu)
     {
          for (int col = 0; col < M->nu; col++)
               num[col] = 0;
          for (int t = 0; t < M->tu; t++)
               num[M->data[t].j]++;
          cpot[0] = 0;
          for (int col = 1; col < M->nu; col++)
               cpot[col] = cpot[col - 1] + num[col - 1];
          int q = 0;
          for (int p = 0; p < M->tu; p++)
          {
               int col = M->data[p].j;
               q = cpot[col]; //根据原列数得到新三元式的起始位置
               N->data[q].e = M->data[p].e;
               N->data[q].i = M->data[p].j;
               N->data[q].j = M->data[p].i;
               cpot[col]++; //起始位置加一
          }
     }
     free(num);
     free(cpot);
}